#!/bin/bash

# cleanup_inactive_users.sh
# 功能说明:
# 1. 检查并清理系统中超过指定时间未登录的用户。
# 2. 支持模拟模式，仅列出需要清理的用户而不实际删除。
# 3. 排除系统用户和关键用户，避免误删除。

# 默认超过多少天未登录的用户会被清理
DEFAULT_INACTIVE_DAYS=90

# 排除的用户组或特定用户
EXCLUDED_USERS=("root" "nobody" "systemd-network" "systemd-resolve")

# 获取用户最后登录时间并判断是否超过指定天数
find_inactive_users() {
  local days="$1"

  echo "Checking for users inactive for more than $days days..."
  local current_date=$(date +%s)
  local inactive_users=()

  # 遍历所有非系统用户
  while IFS=: read -r username _ _ _ _ _ home shell; do
    # 忽略无效或系统用户
    if [[ "$shell" == "/sbin/nologin" || "$shell" == "/usr/sbin/nologin" || "$shell" == "/bin/false" ]]; then
      continue
    fi

    # 排除特定用户
    if [[ " ${EXCLUDED_USERS[*]} " =~ " $username " ]]; then
      continue
    fi

    # 检查用户的最后登录时间
    last_login=$(lastlog -u "$username" | awk 'NR==2 {print $4, $5, $6}')
    if [[ -z "$last_login" || "$last_login" == "**Never logged in**" ]]; then
      echo "User $username has never logged in. Adding to inactive list."
      inactive_users+=("$username")
      continue
    fi

    # 计算用户的最后登录时间
    last_login_date=$(date -d "$last_login" +%s 2>/dev/null)
    if [[ $? -ne 0 ]]; then
      echo "Failed to parse last login date for user $username. Skipping..."
      continue
    fi

    days_inactive=$(( (current_date - last_login_date) / 86400 ))
    if [[ "$days_inactive" -gt "$days" ]]; then
      echo "User $username has been inactive for $days_inactive days. Adding to inactive list."
      inactive_users+=("$username")
    fi
  done < /etc/passwd

  echo "${inactive_users[@]}"
}

# 删除用户
delete_users() {
  local users=("$@")

  for user in "${users[@]}"; do
    echo "Deleting user $user..."
    sudo userdel -r "$user" && echo "User $user has been deleted." || echo "Failed to delete user $user."
  done
}

# 主函数
main() {
  local inactive_days="$DEFAULT_INACTIVE_DAYS"
  local simulate=false

  # 解析命令行参数
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -d|--days)
        shift
        inactive_days="$1"
        ;;
      -s|--simulate)
        simulate=true
        ;;
      -h|--help)
        echo "Usage: $0 [-d days] [-s]"
        echo "  -d, --days       Specify the number of inactive days (default: $DEFAULT_INACTIVE_DAYS)."
        echo "  -s, --simulate   Simulate the cleanup, only list inactive users without deleting them."
        echo "  -h, --help       Display this help message."
        exit 0
        ;;
      *)
        echo "Invalid argument: $1"
        exit 1
        ;;
    esac
    shift
  done

  # 查找超过指定天数未登录的用户
  inactive_users=$(find_inactive_users "$inactive_days")

  if [[ -z "$inactive_users" ]]; then
    echo "No inactive users found."
    exit 0
  fi

  # 模拟模式
  if [[ "$simulate" == true ]]; then
    echo "Simulate mode: The following users would be deleted:"
    echo "$inactive_users"
    exit 0
  fi

  # 实际删除用户
  echo "The following users will be deleted:"
  echo "$inactive_users"
  read -p "Are you sure you want to proceed? (yes/no): " confirm
  if [[ "$confirm" == "yes" ]]; then
    delete_users $inactive_users
  else
    echo "Cleanup aborted."
    exit 0
  fi
}

# 执行主函数
main "$@"

